package week_2.practice;

import java.util.LinkedList;
import java.util.Queue;

public class Codes {
    public static void main(String[] args) {
        //消息的密钥
        int[] key = {5, 12, -3, 8, -9, 4, 10};
        Integer keyValue;
        String enCoded = "", deCoded = "";
        //待加密的字符串
        String message = "All programmers are playWrights and all" +
                " computers are lousy actors.";
        //用于存储密钥的队列
        LinkedQueue<Integer> keyQueue1 = new LinkedQueue<>();
        LinkedQueue<Integer> keyQueue2 = new LinkedQueue<>();

        //两个队列分别存储一份密钥，模拟消息编码者使用一份密钥，消息解码者使用一份密钥
        for(int scan = 0; scan < key.length; scan++){
            keyQueue1.enqueue(key[scan]);
            keyQueue2.enqueue(key[scan]);
        }
        //利用队列存储密钥使得密钥重复很容易，只要在用到每个密钥值后将其放回到队列即可
        for(int scan = 0; scan < message.length(); scan++){
            //取一个密钥
            keyValue = keyQueue1.dequeue();
            //会将该字符移动Unicode字符集的另外一个位置
            enCoded += (char)((int)message.charAt(scan) + keyValue.intValue());
            //将密钥重新存储到队列中
            keyQueue1.enqueue(keyValue);
        }
        System.out.println("Encoded Message:\n"+enCoded+"\n");

        for(int scan = 0; scan < enCoded.length(); scan++){
            keyValue = keyQueue2.dequeue();
            deCoded += (char)((int)enCoded.charAt(scan) - keyValue.intValue());
            keyQueue2.enqueue(keyValue);
        }
        System.out.println("Decoded Message:\n"+deCoded);

    }
}
